<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item label="司机所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item :table-form-merge="1.2">
        <el-input v-model.trim="query.param" style="width: 300px;" placeholder="请输入" clearable>
          <el-select slot="prepend" v-model="qtype" style="width: 140px;" placeholder="请选择">
            <el-option label="绑定司机编号" value="driverCode" />
            <el-option label="绑定司机姓名" value="driverName" />
            <el-option label="值班司机编号" value="dutyDriverCode" />
            <el-option label="值班司机姓名" value="dutyDriverName" />
            <el-option label="值班押运员编号" value="escortCode" />
            <el-option label="值班押运员姓名" value="escortName" />
            <el-option label="客户姓名" value="csmName" />
            <el-option label="客户编号" value="csmCode" />
            <el-option label="客户电话" value="csmPhone" />
          </el-select>
        </el-input>
      </el-form-item>
      <el-form-item label="用户类型:">
        <el-select v-model="query.csmType" placeholder="请选择">
          <el-option v-for="(item,index) in customerTypeMap" :key="index" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="押金类型:">
        <el-select v-model="query.depositType" placeholder="请选择">
          <el-option v-for="item in depositTypeMap" :key="item.value" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[50203,1]"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="[50203,2]" type="primary" icon="el-icon-circle-plus-outline" @click="addCsm">新增用户</el-button>
        <el-button v-permission="[50203,5]" type="primary" icon="el-icon-paperclip" @click="openBatchSwitch">批量切换</el-button>
        <el-button v-permission="[50203,6]" type="primary" icon="el-icon-document-delete" @click="openBatchUnbind">批量解绑</el-button>
        <el-button v-permission="[50203,7]" type="primary" icon="el-icon-upload2" @click="openBatchImport">批量导入</el-button>
        <el-button v-permission="[50203,8]" type="primary" icon="el-icon-download" @click="showExportFile">批量导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <el-dialog
      v-el-drag-dialog
      title="切换绑定司机"
      :visible.sync="visible"
      width="824px"
      @closed="reset"
    >
      <el-descriptions title="用户信息" size="medium" :column="2" :label-style="labelStyle" :content-style="contentStyle">
        <el-descriptions-item label="用户所属机构" style="width: 50%;">{{ dataForm.csmOrgName }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ dataForm.csmName }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="原司机信息" size="medium" :column="2" :label-style="labelStyle" :content-style="contentStyle">
        <el-descriptions-item label="原司机所属机构" style="width: 50%;">{{ dataForm.orgName }}</el-descriptions-item>
        <el-descriptions-item label="原司机">{{ dataForm.driverName }}</el-descriptions-item>
      </el-descriptions>
      <div style=" font-size: 16px; font-weight: 700; color: #303133;">新司机信息</div>
      <el-form ref="dataForm" class="form" :model="dataForm" :rules="rules" label-position="left">
        <el-form-item label="新司机所属机构:" prop="orgSNNo">
          <el-tree-select
            v-model="dataForm.orgSNNo"
            class="tree-select"
            clearable
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': false,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChangeNew"
            @select-clear="selectClearable"
          />
        </el-form-item>
        <el-form-item label="新司机:" prop="newDriverCode">
          <el-select v-model="dataForm.newDriverCode" filterable placeholder="请选择">
            <el-option
              v-for="item in driverList"
              :key="item.userCode"
              :label="item.userName"
              :value="item.userCode"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="danger" @click="cancel('dataForm')">
          取消
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="sumbit('dataForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量导出" :visible.sync="dialogFormVisible" width="424px">
      <el-radio-group v-model="radio">
        <el-radio :label="1">导出当前页数据</el-radio>
        <el-radio :label="2">导出全部数据</el-radio>
      </el-radio-group>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="exportFile">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :title="switchFileFinish ? '批量切换司机用户完成' : '批量切换司机用户'"
      :visible.sync="visibleBatchSwitch"
      width="724px"
    >
      <div v-if="!switchFileFinish">
        <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          :file-list="switchFileList"
          :on-change="switchFileChange"
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
        >
          <el-button icon="el-icon-upload2" size="small" type="primary">点击上传文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
        </el-upload>
        <el-button type="primary" plain icon="el-icon-download" size="small" class="down-btn" @click="downloadTemplate('csmDriverUpdateTemplate', '批量切换司机用户模板')">下载模板</el-button>
        <div class="tip">提示：切换绑定司机之后，这些用户会绑定到新的司机身上，不能自动恢复</div>
      </div>
      <div v-else>
        <div>{{ successNum }}条批量切换司机用户成功，<span class="red">{{ loseNum }}</span>条失败</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => visibleBatchSwitch = false"><span v-if="!switchFileFinish">取消</span><span v-else>知道了</span></el-button>
        <el-button v-if="!switchFileFinish" :loading="$loadingPlugin.saveSwitch" type="primary" @click="saveSwitch">确 认</el-button>
        <el-button v-if="switchFileFinish && loseUrl" type="primary" @click="downloadLoseFile">下载失败数据</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :title="exportFileFinish ? '批量导入司机用户完成' : '批量导入司机用户'"
      :visible.sync="visibleBatchExport"
      width="724px"
    >
      <div v-if="!exportFileFinish">
        <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          :file-list="exportFileList"
          :on-change="exportFileChange"
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
        >
          <el-button icon="el-icon-upload2" size="small" type="primary">点击上传文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
        </el-upload>
        <el-button type="primary" plain icon="el-icon-download" size="small" class="down-btn" @click="downloadTemplate('csmDriverImportTemplate', '批量导入司机用户模板')">下载模板</el-button>
        <div class="tip">提示：批量导入之后，这些用户会绑定到司机身上，不能自动恢复</div>
      </div>
      <div v-else>
        <div>{{ successNum }}条批量导入司机用户成功，<span class="red">{{ loseNum }}</span>条失败</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => visibleBatchExport = false"><span v-if="!exportFileFinish">取消</span><span v-else>知道了</span></el-button>
        <el-button v-if="!exportFileFinish" :loading="$loadingPlugin.saveExport" type="primary" @click="saveExport">确 认</el-button>
        <el-button v-if="exportFileFinish && loseUrl" type="primary" @click="downloadLoseFile">下载失败数据</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :title="unbindFileFinish ? '批量解绑司机用户完成' : '批量解绑司机用户'"
      :visible.sync="visibleBatchUnbind"
      width="724px"
    >
      <div v-if="!unbindFileFinish">
        <el-upload
          class="upload-demo"
          action=""
          :auto-upload="false"
          :file-list="unbindFileList"
          :on-change="unbindFileChange"
          :limit="1"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
        >
          <el-button icon="el-icon-upload2" size="small" type="primary">点击上传文件</el-button>
          <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
        </el-upload>
        <el-button type="primary" plain icon="el-icon-download" size="small" class="down-btn" @click="downloadTemplate('csmDriverUnbindTemplate', '批量解绑司机用户模板')">下载模板</el-button>
        <div class="tip">提示：批量解绑司机之后，这些用户会被释放，今后这些用户就不属于该司机</div>
      </div>
      <div v-else>
        <div>{{ successNum }}条批量解绑司机用户成功，<span class="red">{{ loseNum }}</span>条失败</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => visibleBatchUnbind = false"><span v-if="!unbindFileFinish">取消</span><span v-else>知道了</span></el-button>
        <el-button v-if="!unbindFileFinish" :loading="$loadingPlugin.saveUnbind" type="primary" @click="saveUnbind">确 认</el-button>
        <el-button v-if="unbindFileFinish && loseUrl" type="primary" @click="downloadLoseFile">下载失败数据</el-button>
      </div>
    </el-dialog>
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
    <add-csm
      ref="addCsm"
      :tree-data="treeData"
      :customer-type-map="customerTypeMap"
      :parent-fetch-data="refresh"
    />
  </div>
</template>

<script>
  import {
    queryMap,
    queryBindcsmDriverList,
    csDeliverUserList,
    changeBindcsmDriver,
    unBindcsmDriver,
    exportBindcsmDriver,
    queryExportDomain,
    importBindcsmDriver,
    importUnBindcsmDriver,
    importUpdatecsmDriver
  } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { downLoad } from '@/utils/file'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  import AddCsm from './components/addCsm.vue'
  export default {
    name: '',
    components: {
      CsmDetail,
      AddCsm
    },
    data() {
      return {
        treeData: [],
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方式枚举
        customerTypeMap: [],
        depositTypeMap: [
          { desc: '50型押金用户', value: 1 },
          { desc: '非50型押金用户', value: 2 },
          { desc: '无押金用户', value: 3 },
          { desc: '混合型押金用户', value: 4 }
        ],
        qtype: null,
        query: {
          orgSNNo: null,
          csmType: null,
          depositType: null,
          param: ''
        },
        tableData: {
          total: 0,
          data: []
        },
        visible: false,
        visibleBatchSwitch: false,
        visibleBatchExport: false,
        visibleBatchUnbind: false,
        driverList: [],
        dataForm: {
          orgSNNo: '',
          driverCode: '',
          driverName: '',
          newDriverCode: ''
        },
        rules: {
          orgSNNo: [{ required: true, message: '请选择机构', trigger: 'change' }],
          newDriverCode: [{ required: true, message: '请选择司机', trigger: 'change' }]
        },
        labelStyle: { 'white-space': 'nowrap' },
        contentStyle: { 'word-break': 'break-all' },
        dialogFormVisible: false,
        radio: null,
        switchFileList: [],
        switchFileFinish: false,
        exportFileList: [],
        exportFileFinish: false,
        unbindFileList: [],
        unbindFileFinish: false,
        successNum: 0,
        loseNum: 0,
        loseUrl: ''
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '绑定司机编号',
            prop: 'driverCode',
            width: 110
          },
          {
            label: '绑定司机',
            prop: 'driverName'

          },
          {
            label: '司机所属机构',
            prop: 'orgName',
            showOverflowTooltip: true
          },
          {
            label: '用户编号',
            prop: 'csmCode',
            width: 110,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          )
          },
          {
            label: '用户姓名',
            prop: 'csmName',
            width: 110,
            showOverflowTooltip: true
          },
          {
            label: '用户电话',
            prop: 'csmPhone',
            width: 110
          },
          {
            label: '联系地址',
            prop: 'csmAddress',
            showOverflowTooltip: true
          },
          {
            label: '用户所属机构',
            prop: 'csmOrgName',
            showOverflowTooltip: true
          },
          {
            label: '用户类型',
            prop: 'csmType',
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', Number(row.csmType), 'desc') }</span>
          },
          {
            label: '用户押金类型',
            prop: 'depositType',
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.depositType && formatColumnMap(this.depositTypeMap, 'value', row.depositType, 'desc') }</span>
          },
          {
            label: '值班司机编号',
            prop: 'dutyDriverCode'
          },
          {
            label: '值班司机',
            prop: 'dutyDriverName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.dutyDriverName ? <span style = { !row.orderReceiver ? 'color:#04CDC1' : ''}>{!row.orderReceiver ? `${row.dutyDriverName}（接单）` : `${row.dutyDriverName}`}</span> : <span></span>
            )
          },
          {
            label: '值班押运员编号',
            prop: 'escortCode'
          },
          {
            label: '值班押运员',
            prop: 'escortName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.escortName ? <span style = { row.orderReceiver ? 'color:#04CDC1' : ''}>{row.orderReceiver ? `${row.escortName}（接单）` : `${row.escortName}`}</span> : <span></span>
            )
          },
          {
            label: '操作',
            className: 'action-col',
            width: 120,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
              <div>
                  <el-link
                    v-permission={[50203, 3]}
                    underline={false}
                    size='mini'
                    onClick={() => this.bind(row, $index)}
                  >
                    切换司机
                  </el-link>
                  <el-link
                    v-permission={[50203, 4]}
                    underline={false}
                    size='mini'
                    type='danger'
                    onClick={() => this.noBind(row, $index)}
                  >
                    解绑
                  </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      this.getTreeData()
      await Promise.all([this.queryOptionsMap()])
      this.getExportDomain()
      this.$nextTick(() => {
        this.$refs.lbTable.fetch()
      })
    },
    beforeDestroy() {
    },
    methods: {
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        ])
        this.calcTypeList = res1.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res2.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.customerTypeMap = res3.data // 客户类型
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      async selectTreeChange(value) {
        this.query.orgId = value.orgId
        this.query.orgName = value.orgName
      },
      // 切换司机选择所属机构
      async selectTreeChangeNew(value) {
        this.driverList = []
        // this.dataForm.orgId = value.orgId
        // this.dataForm.orgName = value.orgName
        const res = await csDeliverUserList({ deliveryOrgId: value.orgId, utype: 8388640 })
        if (res.data) {
          this.driverList = res.data.filter(item => item.userCode !== this.dataForm.driverCode)
        }
      },
      selectClearable() {
        this.dataForm.newDriverCode = ''
        this.driverList = []
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        // query.orgId = this.query.option ? 0 : this.query.orgId
        return query
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage, pageSize }) {
        this.pageSize = pageSize
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const res = await queryBindcsmDriverList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      search() {
        if (!this.qtype && this.query.param) {
          this.$message.warning('请选择查询条件')
          return
        }
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 打开详情
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      // 切换绑定司机
      async bind(row) {
        this.dataForm.csmName = row.csmName
        this.dataForm.csmId = row.csmId
        this.dataForm.csmOrgName = row.csmOrgName
        this.dataForm.driverName = row.driverName
        this.dataForm.driverCode = row.driverCode
        this.dataForm.orgSNNo = row.orgSNNo
        this.dataForm.orgId = row.orgId
        this.dataForm.orgName = row.orgName
        await this.selectTreeChangeNew(row)
        this.visible = true
      },
      // 解绑
      noBind(row) {
        this.$confirm(`此操作会将机构<strong style="color:red">${row.orgName}</strong>下的司机<strong style="color:red">${row.driverName}</strong>绑定的用户<strong style="color:red">${row.csmName}</strong>释放，今后该用户就不属于该司机, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning'
        }).then(() => {
          unBindcsmDriver({ driverCode: row.driverCode, csmId: row.csmId }).then(res => {
            this.$notify({
              title: '提示',
              message: '解绑成功!',
              type: 'success',
              duration: 2000
            })
            this.$refs.lbTable.fetch()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消解绑'
          })
        })
      },
      // 取消
      async cancel(formName) {
        await this.reset()
        this.visible = false
      },
      // 保存
      sumbit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const form = {
              driverCode: this.dataForm.driverCode,
              newDriverCode: this.dataForm.newDriverCode,
              csmId: this.dataForm.csmId
            }
            console.log(form)
            changeBindcsmDriver(form).then(res => {
              this.$notify({
                title: '提示',
                message: '切换成功',
                type: 'success',
                duration: 2000
              })
              this.visible = false
              this.$refs.lbTable.fetch()
            }).catch(err => {
              // this.$message.error(err.message)
              console.log(err)
              this.visible = false
            })
          } else {
            return false
          }
        })
      },
      reset() {
        this.$refs.dataForm.resetFields()
        this.driverList = []
        this.dataForm = {
          orgSNNo: '',
          driverCode: null,
          newDriverCode: null
        }
      },
      // 新增用户
      async addCsm() {
        await this.$refs.addCsm.open()
      },
      showExportFile() {
        this.dialogFormVisible = true
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 批量导出
      async exportFile() {
        if (!this.radio) {
          this.$message.error('请选择导出数据的方式')
          return
        }
        var list = JSON.parse(JSON.stringify(this.column))
        list.pop()
        list.shift()
        const value = {}
        await list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        const query = this._getQuery(this.query)
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const params = {
          pageSize: this.radio === 2 ? 0 : this.pageSize,
          paramInfo: {
            ...query
          },
          kv: value
        }
        await exportBindcsmDriver(params).then((res) => {
          window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          this.dialogFormVisible = false
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.orderStatus === 7) {
          return 'danger-row'
        }
        return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 打开批量切换司机弹窗
      openBatchSwitch() {
        this.switchFileList = []
        this.switchFileFinish = false
        this.successNum = 0
        this.loseNum = 0
        this.loseUrl = ''
        this.visibleBatchSwitch = true
      },
      switchFileChange(file, fileList) {
        this.switchFileList = fileList
      },
      // 批量切换司机保存
      async saveSwitch() {
        if (this.switchFileList.length > 0) {
          const formData = new FormData()
          formData.append('file', this.switchFileList[0].raw)
          const res = await importUpdatecsmDriver(formData)
          if (res.data) {
            this.successNum = res.data.successNum
            this.loseNum = res.data.loseNum
            this.loseUrl = res.data.url
            this.switchFileFinish = true
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        } else {
          this.$message.warning('请先上传文件')
        }
      },
      // 打开批量导入司机弹窗
      openBatchImport() {
        this.exportFileList = []
        this.exportFileFinish = false
        this.successNum = 0
        this.loseNum = 0
        this.loseUrl = ''
        this.visibleBatchExport = true
      },
      exportFileChange(file, fileList) {
        this.exportFileList = fileList
      },
      // 批量导入司机保存
      async saveExport() {
        if (this.exportFileList.length > 0) {
          const formData = new FormData()
          formData.append('file', this.exportFileList[0].raw)
          const res = await importBindcsmDriver(formData)
          if (res.success) {
            this.successNum = res.data.successNum
            this.loseNum = res.data.loseNum
            this.loseUrl = res.data.url
            this.exportFileFinish = true
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        } else {
          this.$message.warning('请先上传文件')
        }
      },
      // 打开批量解绑司机弹窗
      openBatchUnbind() {
        this.unbindFileList = []
        this.unbindFileFinish = false
        this.successNum = 0
        this.loseNum = 0
        this.loseUrl = ''
        this.visibleBatchUnbind = true
      },
      unbindFileChange(file, fileList) {
        this.unbindFileList = fileList
      },
      // 批量解绑司机保存
      async saveUnbind() {
        if (this.unbindFileList.length > 0) {
          const formData = new FormData()
          formData.append('file', this.unbindFileList[0].raw)
          const res = await importUnBindcsmDriver(formData)
          if (res.success) {
            this.successNum = res.data.successNum
            this.loseNum = res.data.loseNum
            this.loseUrl = res.data.url
            this.unbindFileFinish = true
            this.$refs.lbTable.fetch({ currentPage: 1 })
          }
        } else {
          this.$message.warning('请先上传文件')
        }
      },
      handleExceed(files, fileList) {
        this.$message.warning('当前限制选择 1 个文件')
      },
      // 下载模板
      downloadTemplate(name, fileName) {
        const aUrl = `${window.location.href.split('#')[0]}proxy/driver/bindcsm/download/template?fileName=` + name
        const x = new XMLHttpRequest()
        x.open('GET', aUrl, true)
        x.responseType = 'blob'
        x.onload = function(e) {
          const url = window.URL.createObjectURL(x.response)
          const elink = document.createElement('a')
          elink.href = url
          elink.target = '_self'
          elink.download = fileName + '.xls'
          elink.style.display = 'none'
          document.body.appendChild(elink)
          setTimeout(() => {
            elink.click()
            document.body.removeChild(elink)
          }, 66)
        }
        x.send()
      },
      // 下载失败数据
      downloadLoseFile() {
        downLoad(this.loseUrl)
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    display: flex;
    width: 50%;
    padding-right: 10px;
    // .el-form-item__content {
    //   width: 100%;
    // }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffdfdf;
}
.down-btn {
  position: absolute;
  top: 62px;
  left: 590px;
}
.tip {
  margin-top: 20px;
  color: #F56C6C;
}
.red {
  color: #F56C6C;
}
</style>
